<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:topic:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >新增任务
        </el-button>
      </el-col>
    </el-row>

    <el-collapse @change="collapseChange">
      <el-collapse-item :title="topic.topicName" name="0">
        <el-form ref="topicForm" :disabled="true" :model="topic" label-width="80px" size="mini">
          <el-form-item label="课题编号" prop="topicCode">
            <el-input v-model="topic.topicCode" placeholder="请输入课题编号"/>
          </el-form-item>
          <el-form-item label="课题名称" prop="topicName">
            <el-input v-model="topic.topicName" placeholder="请输入课题名称"/>
          </el-form-item>
          <el-form-item label="课题来源" prop="topicSource">
            <el-input v-model="topic.topicSource" placeholder="请输入课题来源"/>
          </el-form-item>
          <el-form-item label="研究目的" prop="researchPurposes">
            <el-input v-model="topic.researchPurposes" placeholder="请输入内容" type="textarea"/>
          </el-form-item>
          <el-form-item label="研究方法" prop="researchMethod">
            <el-input v-model="topic.researchMethod" placeholder="请输入内容" type="textarea"/>
          </el-form-item>
          <el-form-item label="预期结果" prop="expectedResult">
            <el-input v-model="topic.expectedResult" placeholder="请输入内容" type="textarea"/>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker v-model="topic.startTime" clearable
                            placeholder="选择开始时间"
                            size="small"
                            type="date"
                            value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker v-model="topic.endTime" clearable
                            placeholder="选择结束时间"
                            size="small"
                            type="date"
                            value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </el-collapse-item>
      <el-collapse-item v-if="topic.formKey" name="1" title="临床报告CRF表">
        <div
          v-for="(domain, index) in customForm.formJson"
          :key="index"
          :label="domain.controlLable"
        >
          <parser ref="formCustom" :form-conf="domain.json"/>
        </div>
        <!--        <el-button type="primary" @click="submitCrfForm" size="small">提 交</el-button>-->
        <!--        <el-button @click="excelPdf" size="small">导 出</el-button>-->
      </el-collapse-item>
      <!--      <el-button type="primary" @click="submitCrfForm" size="small" v-hasPermi="['research:task:crf:update']">提 交</el-button>-->
      <!--      <el-button @click="excelPdf" v-hasPermi="['research:task:crf:export']" size="small">导 出</el-button>-->
      <el-button v-if="collapseKey" v-hasPermi="['research:task:crf:update']" size="small"
                 style="margin-top: 10px;margin-bottom: 10px" type="primary" @click="submitCrfForm"
      >提 交
      </el-button>
      <el-button v-if="collapseKey" v-hasPermi="['research:task:crf:export']" size="small"
                 style="margin-top: 10px;margin-bottom: 10px" @click="excelPdf"
      >导 出
      </el-button>
    </el-collapse>

    <el-timeline style="margin-top: 16px">
      <el-timeline-item
        v-for="(task, index) in taskList"
        :key="index"
        :color="task.taskState === '0' ? '#999999': '#0bbd87'"
        :icon="task.taskState === '0' ? null: 'el-icon-check'"
        :timestamp="task.createTime"
        placement="top"
        size="large"
      >
        <el-card style="position: relative">
          <div slot="header" class="clearfix">
            <span>{{ task.taskName }}</span>
            <el-button icon="el-icon-delete" style="float: right; padding: 3px 0" type="text"
                       @click="handleDelete(task)"
            >删除
            </el-button>
            <el-button style="float: right; padding: 3px 0; margin-right: 16px" type="text"
                       @click="addSampleTaskRelate(task)"
            >
              <svg-icon icon-class="relate"></svg-icon>
              关联
            </el-button>
            <el-button icon="el-icon-edit" style="float: right; padding: 3px 0" type="text" @click="handleUpdate(task)">
              编辑
            </el-button>
          </div>
          <p><span v-html="task.taskDesc"/></p>
          <div v-if="task.attaches && task.attaches.length > 0" style="margin-top: 7px">
            <div v-for="(item, index) in task.attaches">
              <el-link type="primary" @click="attachView(item)">{{ item.fileName }}</el-link>
            </div>
          </div>
          <el-table v-if="task.sampleBackups && task.sampleBackups.length > 0" :data="task.sampleBackups"
                    max-height="240" size="mini" style="margin-top: 10px"
          >
            <el-table-column align="center" label="关联样本复份编号" min-width="110" prop="sampBackupCode"/>
            <el-table-column align="center" label="样本类型" prop="sampTypeName"/>
            <el-table-column align="center" label="样本源名称" prop="sampSourceName"/>
            <el-table-column align="center" label="样本源类型" prop="sampSourceTypeName"/>
            <el-table-column align="center" label="样本组" prop="sampGroupName"/>
            <el-table-column align="center" label="冻融次数" prop="sampFreezeThawCount"/>
            <el-table-column align="center" label="关联样本位置" prop="sampLocation" width="520"/>
            <el-table-column align="center" label="条码/二维码" prop="qrCode"/>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="cancelTaskSampleRelate(scope.row, task)"
                >
                  <svg-icon icon-class="unrelate"></svg-icon>
                  取消关联
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="handleView(scope.row, task)"
                >
                  <svg-icon icon-class="eye-open"></svg-icon>
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-timeline-item>
    </el-timeline>

    <task-preview :customForm="customForm" :previewVisible.sync="previewVisible" :topic="topic"
                  @closePreview="closePreview"
    ></task-preview>

    <!-- 添加或修改课题任务 对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="900px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称"/>
        </el-form-item>
        <el-form-item label="任务状态" prop="taskState">
          <el-switch v-model="form.taskState"
                     active-text="完成"
                     active-value="1"
                     inactive-text="未完成"
                     inactive-value="0"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <editor v-model="form.taskDesc" :min-height="200"/>
      <file-upload :value="form.attaches" style="margin-top: 16px" @fileEvent="fileUploadEvent"></file-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 挑选样本对话框 -->
    <sample-pick :open="pickOpen" :value="selectTask.sampleBackups" samp-state="1,2,3,4,5,6,7"
                 @onClose="samplePickClose" @onConfirm="samplePickEvent"
    ></sample-pick>

    <!--查看样本对话框-->
    <el-dialog :visible.sync="showOpen" append-to-body title="样本复份详情" width="70%">
      <div class="scrollbar" style="height:700px;">
        <el-scrollbar style="height:100%">
          <el-row>
            <el-col :span="7">
              <div>
                <label class="samp-label">样本复份编号 </label>
                <span class="samp-value">{{ sampleDetails.sampBackupCode }}</span>
              </div>
              <div>
                <span class="samp-label">样本状态 </span>
                <span class="samp-value">{{ sampStateFormat(sampleDetails) }}</span>
              </div>
              <div>
                <span class="samp-label">样本量 </span>
                <span class="samp-value">{{ sampleDetails.sampQuantity }}</span>
              </div>
              <div>
                <span class="samp-label">样本单位 </span>
                <span class="samp-value">{{ sampleDetails.sampUnit }}</span>
              </div>
              <div>
                <span class="samp-label">格式化位置 </span>
                <span class="samp-value">{{ sampleDetails.sampLocation }}</span>
              </div>
              <div>
                <span class="samp-label">冻融次数 </span>
                <span class="samp-value">{{ sampleDetails.sampFreezeThawCount }}</span>
              </div>
              <div>
                <span class="samp-label">采样时间 </span>
                <span class="samp-value">{{ sampleDetails.samplingTime }}</span>
              </div>
              <div>
                <span class="samp-label">条码/二维码 </span>
                <span class="samp-value">{{ sampleDetails.qrCode }}</span>
              </div>
              <div>
                <span class="samp-label">贴码管/预置管 </span>
                <span class="samp-value">{{ tubeTypeFormat(sampleDetails) }}</span>
              </div>
            </el-col>
            <el-col :span="0.5">
              <el-divider direction="vertical"></el-divider>
            </el-col>
            <el-col :span="8">
              <div>
                <span class="samp-label">样本源编号</span>
                <span class="samp-value">{{ sourceDetails.sourceCode }}</span>
              </div>
              <div>
                <span class="samp-label">样本源类型 </span>
                <span class="samp-value">{{ sourceDetails.sourceTypeName }}</span>
              </div>
              <div>
                <span class="samp-label">样本源名称 </span>
                <span class="samp-value">{{ sourceDetails.sourceName }}</span>
              </div>
              <div>
                <span class="samp-label">样本源描述 </span>
                <span class="samp-value">{{ sourceDetails.sourceDesc }}</span>
              </div>
              <div>
                <span class="samp-label">随访状态 </span>
                <span class="samp-value">{{ followStateFormat(sourceDetails) }}</span>
              </div>
              <el-collapse v-model="activeNames">
                <el-collapse-item :name="1">
                  <!-- <template slot="title">自定义表单<i class="el-icon-s-promotion"></i></template> -->
                  <el-divider><i class="el-icon-s-promotion"></i></el-divider>
                  <div
                    v-for="(domain, index) in form.formJson"
                    :key="index"
                    :label="domain.controlLable"
                  >
                    <parser ref="formCustom" :form-conf="domain.json"/>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-col>
            <el-col :span="0.5">
              <el-divider direction="vertical"></el-divider>
            </el-col>
            <el-col :span="8">
              <!-- 生命周期 -->
              <el-timeline :reverse="reverse">
                <el-timeline-item
                  v-for="(activity, index) in lifeCycles"
                  :key="index"
                  :timestamp="activity.updateTime"
                >
                  {{ activity.typeName }} - {{ activity.createName }}
                </el-timeline-item>
              </el-timeline>
            </el-col>
          </el-row>
          <el-divider content-position="center">同样本其他复份信息</el-divider>
          <el-table :data="sameSamples" max-height="280" size="small">
            <el-table-column align="center" label="复份编号" prop="sampBackupCode" width="150"/>
            <el-table-column align="center" label="样本位置" prop="sampLocation" width="450"/>
            <el-table-column align="center" label="条码/二维码" prop="qrCode"/>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-scrollbar>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addRelate, addTask, cancelRelate, delTask, getTask, listTask, updateTask } from '@/api/research/task'
import { getTopic, updateTopic } from '@/api/research/topic'
import { formJsonShow } from '@/api/tool/form'
import Parser from 'form-gen-parser'
import Editor from '@/components/Editor'
import FileUpload from '@/components/FileUpload'
import { getPreviewUrl } from '@/api/oss/minio'
import SamplePick from '@/views/biobank/sample/SamplePick'
import { getSameSamples, getSample, getSampleLifeCycle, getSampSourceInfo } from '@/api/biobank/sample'
import taskPreview from '@/views/research/task/taskPreview'

export default {
  name: 'TopicTask',
  components: {
    Parser,
    Editor,
    FileUpload,
    SamplePick,
    taskPreview
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 课题任务 表格数据
      taskList: [],
      // 弹出层标题
      title: '',
      // 课题
      topic: {},
      // CRF表单
      customForm: {},
      // 是否显示弹出层
      open: false,
      // 挑选样本对话框
      pickOpen: false,
      //是否显示样本源弹出层
      showOpen: false,
      // 选中的任务
      selectTask: {},
      //样本详情数据
      sampleDetails: {},
      //样本源详情
      sourceDetails: {},
      // 样本生命周期
      lifeCycles: [],
      // 同样本其他复份
      sameSamples: [],
      // 样本状态
      sampStateOptions: [],
      //自定义表单折叠面板默认展开值
      activeNames: 1,
      reverse: true,
      // 查询参数
      queryParams: {
        topicId: undefined,
        taskName: undefined,
        taskDesc: undefined,
        taskState: undefined
      },
      // 随访状态
      followStateOptions: [],
      // 冻存管类型
      tubeTypeOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [{ required: true, trigger: 'blur', message: '任务名称不能为空' }, {
          max: 100,
          trigger: 'blur',
          message: '任务名称不能超过100个字符'
        }]
      },

      //预览弹窗
      previewVisible: false,
      collapseKey: false
    }
  },
  created() {
    const topicId = this.$route.query && this.$route.query.topicId
    this.queryParams.topicId = topicId
    getTopic(topicId).then(response => {
      this.topic = response.data
      this.showFormJson(this.topic.formKey)
    })
    this.getList()
  },
  methods: {
    // 选择样本对话框取消事件
    samplePickClose() {
      this.pickOpen = !this.pickOpen
    },
    // 挑选样本
    samplePickEvent(selection) {
      if (!selection || selection.length === 0) {
        this.pickOpen = !this.pickOpen
        return false
      }
      let existSampleIds = this.selectTask.sampleBackups.map(i => i.sampBackupId)
      let params = []
      selection.forEach((item, index) => {
        if (existSampleIds.length === 0 || existSampleIds.indexOf(item.sampBackupId) === -1) {
          let param = {}
          param.taskId = this.selectTask.taskId
          param.sampBackupId = item.sampBackupId
          params.push(param)
        }
      })
      addRelate(params).then(response => {
        this.getList()
        this.msgSuccess('添加关联成功')
        this.pickOpen = !this.pickOpen
      })
    },
    // 新增关联
    addSampleTaskRelate(task) {
      this.pickOpen = true
      this.selectTask = task
    },
    // 取消关联
    cancelTaskSampleRelate(sample, task) {
      this.$confirm('是否确认取消该样本与该任务的关联?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        let param = {}
        param.taskId = task.taskId
        param.sampBackupId = sample.sampBackupId
        return cancelRelate(param)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    // 附件上传子组件回调
    fileUploadEvent(fileList) {
      this.form.attaches = fileList
    },
    // 查看附件
    attachView(value) {
      getPreviewUrl(value.fileUrl).then(response => {
        window.open(response.data)
      })
    },
    // crf表提交
    submitCrfForm() {
      let custFormRef = this.$refs.formCustom[0]
      let custForm = custFormRef.$refs[custFormRef.formConf.formRef]
      let custData = custFormRef[custFormRef.formConf.formModel]
      let custDesc = {}
      for (let onceForm of this.customForm.formJson) {
        for (let onceField of onceForm.json.fields) {
          if (onceField.__vModel__) {
            custDesc[onceField.__vModel__] = onceField.__config__.label
          } else {
            if (onceField.__config__ && onceField.__config__.children && onceField.__config__.children.length > 0) {
              onceField.__config__.children.forEach(child => {
                custDesc[child.__vModel__] = child.__config__.label
              })
            }
          }
        }
      }
      // 自定义表单的核验
      custForm.validate(e => {
        if (e) {
          this.topic.formData = JSON.stringify(custData)
          this.topic.formDesc = JSON.stringify(custDesc)
          updateTopic(this.topic).then(response => {
            this.msgSuccess('临床报告CRF提交成功')
          })
        }
      })
    },
    // 渲染动态表单
    showFormJson(formKey) {
      if (!formKey || formKey === '') {
        return false
      }
      formJsonShow(formKey).then(response => {
        let formJson = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formJson.push({
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.$set(this.customForm, 'formJson', formJson)
        if (this.topic.formData != undefined) {
          this.fillFormData(this.customForm.formJson[0].json, JSON.parse(this.topic.formData))
          this.$set(this.customForm, 'formJson', formJson)
        }
      })
    },
    // 动态表单值回写
    fillFormData(form, data) {
      form.fields.map(item => {
        if (item.__vModel__) {
          const val = data[item.__vModel__]
          if (val) {
            item.__config__.defaultValue = val
          }
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              const childVal = data[child.__vModel__]
              if (childVal) {
                child.__config__.defaultValue = childVal
              }
            })
            return item
          }
        }
      })
    },

    // crf表导出
    excelPdf() {
      this.previewVisible = true
    },

    closePreview() {
      this.previewVisible = !this.previewVisible
    },

    collapseChange(e) {
      let arr = e
      if (arr.includes('1')) {
        this.collapseKey = true
      } else {
        this.collapseKey = false
      }
    },

    /** 查询课题任务 列表 */
    getList() {
      this.loading = true
      listTask(this.queryParams).then(response => {
        this.taskList = response.data
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.selectTask = {}
      this.form = {
        taskId: undefined,
        taskName: undefined,
        taskDesc: undefined,
        taskState: undefined,
        attaches: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加课题任务 '
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const taskId = row.taskId
      getTask(taskId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改课题任务 '
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.form.topicId = this.topic.topicId
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.taskId != null) {
            updateTask(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addTask(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId
      this.$confirm('是否确认删除课题 编号为 ' + taskIds, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delTask(taskIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    // 查看按钮事件
    handleView(row) {
      // this.reset();
      //获取样本状态集
      this.getDicts('sample_state').then(response => {
        this.sampStateOptions = response.data
      })
      //获取随访状态集
      this.getDicts('follow_state').then(response => {
        this.followStateOptions = response.data
      })
      //获取贴码管/预制管集
      this.getDicts('tube_type').then(response => {
        this.tubeTypeOptions = response.data
      })
      this.showOpen = true
      const sampBackupId = row.sampBackupId || this.ids
      getSample(sampBackupId).then(response => {
        this.sampleDetails = response.data
      })
      // 获取样本复份生命周期
      getSampleLifeCycle(sampBackupId).then(response => {
        this.lifeCycles = response.data
      })
      // 获取同样本其他复份信息
      getSameSamples(row).then(response => {
        this.sameSamples = response.data
      })
      // 获取样本源信息及自定义表单
      getSampSourceInfo(row.sampSourceId).then(response => {
        this.sourceDetails = response.data
        //渲染自定义表单
        const formKey = this.sourceDetails.formKey
        const formData = this.sourceDetails.formData
        this.formData = this.formData
        this.showCustomForm(formKey, formData)
      })
    },
    /** 随访状态字典翻译 */
    followStateFormat(row) {
      return this.selectDictLabel(this.followStateOptions, row.followState)
    },
    /** 冻存管类型字典翻译 */
    tubeTypeFormat(row) {
      return this.selectDictLabel(this.tubeTypeOptions, row.tubeType)
    },
    /** 样本状态状态字典翻译 */
    sampStateFormat(row, column) {
      return this.selectDictLabel(this.sampStateOptions, row.sampState)
    },
    /**动态表单展示 */
    showCustomForm(formKey, formData) {
      if (!formKey || formKey === '') {
        this.$set(this.form, 'formJson', undefined)
        return false
      }
      formJsonShow(formKey).then(response => {
        let formJson = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formJson.push({
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.$set(this.form, 'formJson', formJson)
        this.disableForm(this.form.formJson[0].json)
        if (formData != undefined) {
          this.fillFormData(this.form.formJson[0].json, JSON.parse(formData))
          this.$set(this.form, 'formJson', formJson)
        }
      })
    },
    // 设置动态表单禁用状态
    disableForm(form) {
      form.fields.map(item => {
        if (item.__vModel__) {
          item.disabled = true
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              child.disabled = true
            })
            return item
          }
        }
      })
    }
  }
}
</script>
<style scoped>
.el-input /deep/ .el-input__inner {
  color: #888888 !important;
  cursor: pointer;
}

.el-textarea /deep/ .el-textarea__inner {
  color: #888888 !important;
  cursor: pointer;
}

.table-expand {
  font-size: 0;
}

.table-expand label {
  width: 90px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.samp-label {
  width: 100px;
  font-weight: 700;
  text-align: right;
  vertical-align: middle;
  font-size: 14px;
  line-height: 30px;
  display: inline-block;
}

.samp-value {
  font-weight: 100;
  text-align: center;
  vertical-align: middle;
  font-size: 14px;
  line-height: 30px;
  margin-left: 36px;
}

.el-divider--vertical {
  display: inline-block;
  height: 20em;
  border-left: 2px dashed #e8eaec;
  position: relative;
  background: 0 0;
}

/deep/ .el-scrollbar__wrap {
  overflow: scroll;
  width: 110%;
  height: 100%;
}

.el-scrollbar {
  display: flex;
  justify-content: space-around;
  padding: 0 10px;
}

.el-scrollbar__bar.is-horizontal {
  display: none;
}

</style>
